package com.ly.ql.Wms.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ly.ql.Wms.Mapper.InStockBillMapper;
import lombok.RequiredArgsConstructor;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginUtils {
    @Value(value = "${k3.USERNAME}")
    private String userName;

    @Value(value = "${k3.PASSWORD}")
    private String password;

    @Value(value = "${k3.ACCTID}")
    private String acctid;

    @Value(value = "${k3.LCID}")
    private String lcid;

    @Value(value = "${k3.LOGINURL}")
    private String url;



    private final StringRedisTemplate stringRedisTemplate;

    private final HttpRequestContextUtils httpRequestContextUtils;

    private final InStockBillMapper inStockBillMapper;

    /**
     * 返回token
     * @return
     */
    public String getLogin() throws IOException {

        String  result= null;

        String Cookie = stringRedisTemplate.opsForValue().get("Cookie");
        if (Cookie!=null&&!Cookie.isEmpty()){
            result=Cookie;
            return result;
        }
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 装填参数
//        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//        nameValuePairs.add(new BasicNameValuePair("USERNAMEPARA",userName));
//        nameValuePairs.add(new BasicNameValuePair("PASSWORD",password));
//        nameValuePairs.add(new BasicNameValuePair("ACCTID",acctid));
//        nameValuePairs.add(new BasicNameValuePair("LCID",lcid));
        Map map =new HashMap<>();
        map.put("username",userName);
        map.put("password",password);
        map.put("acctID",acctid);
        map.put("lcid",lcid);
        String param = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
        StringEntity stringEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        stringEntity.setContentEncoding("utf-8");
        httpPost.setEntity(stringEntity);
      //  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        //httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都是正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Set-Cookie");
            for (Header header : headers) {
                if (header.getValue().startsWith("kdservice-sessionid")){
                    result=header.getValue();
                    stringRedisTemplate.opsForValue().set("Cookie",result, Duration.ofSeconds(1200));
                }
            }
        }
        return result;
    }

    /**
     * 获取当前人
     * @return
     */
    public Long getUserId(){
        HttpServletRequest request = httpRequestContextUtils.returnHttpRequest();
        Map<String,String> map =new HashMap<>();
        if ("127.0.0.1".equals(request.getRemoteAddr())){
            map.put("Code","109763");
            Long OID = inStockBillMapper.selectIdByCondition("lrp_warehousekeeper", map);
            return OID;
        }
        map.put("Code","LH");
        return inStockBillMapper.selectIdByCondition("lrp_warehousekeeper",map);
    }
}
